package main;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

public class ChiefScientist implements Observer {

	private Repository repository;
	private Vector<HeadOfLaboratory> labHeads;
	private ScienceStore store;
	private ChiefScientistAssistant assistant;
	private ArrayList<Expirement> experimentsList;
	private Statistics stats;

	
	public ChiefScientist(Vector<HeadOfLaboratory> labHeads, ArrayList<Expirement> experimentsList,
	Statistics stats, ScienceStoreImpl store,Repository repository) {	
		this.repository = repository;
		this.labHeads = labHeads;
		this.store = store;
		this.experimentsList = experimentsList;
		this.stats = stats;
		this.assistant =new ChiefScientistAssistant(experimentsList, repository, labHeads, store, stats, this);	
	}

	/**
	 * responisble for starting the simulation of the entire company. will wait until get message from assitant that all experiments finished
	 */
	public void startSimulation() {
	Thread t=new Thread(assistant);
	t.start();
	synchronized(assistant){
		while(!assistant.isExperimentsFinished()){
			try{
				assistant.wait();		//wait on this company head, till his assistant notify him all is done
				System.out.println("main");
			}catch(InterruptedException e)
			{
				System.out.println("INTERRUPTED");
			}	
		}
	}
	
	}
	
	
	public void update(Observable arg0, Object arg1) {
		if(arg1 instanceof Expirement)
		{
			int expStatus=((Expirement) arg1).getStatus();
			if(expStatus==3)		//experiment finished
			{
				finishedExperiment((Expirement) arg1);
			}
			synchronized (experimentsList) {
				experimentsList.notifyAll();
			}
		}
	}
	
	private void finishedExperiment(Expirement exp) {
		//deal with stats and reward
		rewardExperiment(exp);
		stats.addFinishedExperiment(exp);
		//deals with experiment pre requirements
		int id=exp.getID();
		Iterator<Expirement> i=experimentsList.iterator();
		while(i.hasNext())
		{
			Expirement checkedExp=i.next();
			checkedExp.removePrerequiredExperiment(id);
		}
	}
	
	private void rewardExperiment(Expirement exp) {
		if(exp.getRuntime()*1.15 >= exp.getRealtimeRunning())	//we managed to stand at reqvaried time
		{
			System.out.println("exp "+exp.getID()+" was rewarded FULLY:"+exp.getReward());
			stats.addBudget((int)(exp.getReward()));
		}
		else
		{
			System.out.println("exp "+exp.getID()+" was rewarded 10%:"+exp.getReward()*0.10);
			stats.addBudget((int)(exp.getReward()*0.10)); 
		}
	}
}
